﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace YTCMS.Core.Security
{
    public static class SecurityHelper
    {
        /// <summary>
        /// 使用加密服务提供程序 (CSP) 提供的实现来实现加密随机数生成器 (RNG)
        /// </summary>
        /// <returns></returns>
        public static string CreateSalt()
        {
            byte[] array = new byte[16];
            new RNGCryptoServiceProvider().GetBytes(array);
            return Convert.ToBase64String(array);
        }
        /// <summary>
        /// 加密密码
        /// </summary>
        /// <param name="format"></param>
        /// <param name="cleanString"></param>
        /// <param name="salt"></param>
        /// <returns></returns>
        public static string EncodePassword(PasswordFormat format, string cleanString, string salt)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(salt.ToLower() + cleanString);
            string result;
            switch (format)
            {
                case PasswordFormat.Clear:
                    result = cleanString;
                    break;
                case PasswordFormat.Hashed:
                    {
                        byte[] value = ((HashAlgorithm)CryptoConfig.CreateFromName("SHA1")).ComputeHash(bytes);
                        result = BitConverter.ToString(value);
                        break;
                    }
                default:
                    {
                        byte[] value = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(bytes);
                        result = BitConverter.ToString(value);
                        break;
                    }
            }
            return result;
        }
    }
}
